package com.venta.autopartes.vehicle.add;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.venta.autopartes.car.MakeVehicle;
import com.venta.autopartes.car.ModelVehicle;
import com.venta.autopartes.car.YearVehicle;
import com.venta.autopartes.car.SubModelVehicle;
import com.venta.autopartes.car.Vehicle;
import com.venta.autopartes.dao.CurrencyDAO;
import com.venta.autopartes.dao.EquipmentDAO;
import com.venta.autopartes.dao.LocationDAO;
import com.venta.autopartes.dao.UtilitiesDAO;
import com.venta.autopartes.dao.VehicleDAO;
import com.venta.autopartes.menu.LeftFloatingMenu;
import com.venta.autopartes.menu.Menu;
import com.venta.autopartes.menu.Option;
import com.venta.autopartes.user.User;
import com.venta.autopartes.utils.Constants;
import com.venta.autopartes.utils.DataCatalog;
import com.venta.autopartes.utils.FormatUtility;
import com.venta.autopartes.utils.SessionFactory;
import com.venta.autopartes.utils.SessionValidator;
import com.venta.autopartes.utils.TransferFileFTP;

public class GoStartAddVehicleAction extends ActionSupport implements SessionAware,ServletRequestAware{
	private Map session;
	
	private List<File> upload = new ArrayList<File>();
    private List<String> uploadContentType = new ArrayList<String>();
    private List<String> uploadFileName = new ArrayList<String>();
    
    private HttpServletRequest servletRequest;
	
	private Vehicle vehicleForm;
	
	public String goStartAddVehicleMakeModel() {
		
		SessionFactory.removePreviosSessionData();
		return "success";

	}
	
	public String selectMakeVehicle(){
		Vehicle vehicleSelected=this.vehicleForm;
		if (session.get(Constants.VEHICLE_SEARCH_RESULT)!=null){
			/*String make=vehicleForm.getMake().getMakeVehicle();
			String model=vehicleForm.getModel().getModelVehicle();
			String versionSubModel=vehicleForm.getVersionSubModel().getSubModelVehicle();
			String year=vehicleForm.getYear().getYear();
			vehicleForm=(Vehicle)session.get(Constants.VEHICLE_SEARCH_RESULT);
			vehicleForm.setMake(new MakeVehicle(0,make));
			vehicleForm.setModel(new ModelVehicle(0,model));
			vehicleForm.setVersionSubModel(new SubModelVehicle(0,versionSubModel));
			vehicleForm.setYear(new YearVehicle(0,year));*/
			vehicleSelected=(Vehicle)session.get(Constants.VEHICLE_SEARCH_RESULT);
			
			int vehicleId=vehicleSelected.getCarId();
			vehicleSelected=this.vehicleForm.getVehicleClon();
			vehicleSelected.setCarId(vehicleId);
			System.out.println("Vehicle was clonned");
		}
		session.put(Constants.VEHICLE_SEARCH_RESULT, vehicleForm);
		return SUCCESS;
	}
	
	public String addVehicleDetails() {
		
		if(!SessionValidator.isValidSession(session)){
			return SessionValidator.INVALID_SESSION;
		}

		Vehicle vehicleSelected=(Vehicle)session.get(Constants.VEHICLE_SEARCH_RESULT);
		
		DataCatalog dataCatalog=(DataCatalog)session.get(Constants.DATA_CATALOG);
		vehicleSelected.getEquipment().setCharacteristicsList(dataCatalog.getVehicleCharacteristicListBySelectedProperties(this.vehicleForm.getEquipment().getEquipment()));

		updateVehicleSession(this.vehicleForm, vehicleSelected);
	
		
		session.put(Constants.VEHICLE_SEARCH_RESULT, vehicleSelected);
		System.out.println("Nos vamos a cargar imagenes!!!");
		return "success";

	}
	
	public String uploadVehiclePictures() {
		System.out.println("Selected pictures will be uploaded. ");
		
		if(!SessionValidator.isValidSession(session)){
			return SessionValidator.INVALID_SESSION;
		}
		
		//Remove this part of code
		
		if(true){
			return "success";
		}
		
		try {

			// Review this piece of code!!!!
			System.out.println("\n\n upload1");
			System.out.println("files:");
			for (File u : upload) {
				System.out.println("*** " + u + "\t" + u.length());
			}
			System.out.println("filenames:");
			for (String n : uploadFileName) {
				System.out.println("*** " + n);
			}
			System.out.println("content types:");
			if (uploadContentType.size() > 0) {

				for (int i = 0; i < uploadContentType.size(); i++) {

					String c = uploadContentType.get(i);

					System.out.println("*** " + c);

					

				}
				String filePath = servletRequest.getSession()
						.getServletContext().getRealPath("/");
				System.out.println("Server path:" + filePath);

				List<File> renamedFilesList=new ArrayList<File>();
				File fileToCreate;
				
				for (int i=0;i<this.upload.size();i++){
					String fileName = this.upload.get(i).getName();
					
					fileName=FormatUtility.renameFullFileName(fileName, "Test_File_0000000"+i, "jpg");
					fileToCreate= new File(filePath, fileName);
					FileUtils.copyFile(this.upload.get(i), fileToCreate);
					renamedFilesList.add(fileToCreate);
					
				}
				
				
				//String fileName = this.uploads.get(i).getName()
					//	.replaceAll("\\.tmp$", ".jpg");

				//File fileToCreate = new File(filePath, fileName);

				//TransferFileFTP transferFileFTP = new TransferFileFTP("ftp.260mb.com","pacus_3798589","860523",21,"/htdocs/images/testFTPjava");
				TransferFileFTP transferFileFTP = new TransferFileFTP("127.0.0.1","luis","luis",21,null);
				transferFileFTP.setFileType(transferFileFTP.BINARY_FILE_TYPE);
				
				System.out.println(transferFileFTP.sendFile(renamedFilesList));
				
				
				session.put("uploadFileName", uploadFileName);
				
				for(String uploadFileNameString:uploadFileName){
					System.out.println(uploadFileNameString);
				}
				
				return "success";
			}
			System.out.println("\n\n");

		} catch (Exception ex) {
			ex.printStackTrace();
			addActionError(ex.getMessage());

			return INPUT;
		}

		return INPUT;
	}
	
	public String addVehicleRegister() {
		boolean result=false;
		VehicleDAO vehicleDAO=new VehicleDAO();
		
		Vehicle sessionVehicle=(Vehicle)session.get("vehicle");

		result =true;
		if(sessionVehicle.getCarId()>0){
			System.out.println("Vehicle selected " + sessionVehicle.getCarId() + ", will be updated in Database");
			result=vehicleDAO.updateVehicle(sessionVehicle);
		}else{
			System.out.println("A new vehicle will be added in Database ->" + sessionVehicle.getMake() + " - " + sessionVehicle.getModel());
			List<Vehicle> vehiclesListSearch=(List<Vehicle>)session.get("vehiclesListSearch");//Remove this line
			vehiclesListSearch.add(sessionVehicle); //Remove this line
			session.put("vehiclesListSearch", vehiclesListSearch);//Remove this line
			
			//result=vehicleDAO.insertVehicle(sessionVehicle);
		}
		
		
		
		if(result){
			System.out.println("Vehicle has been register correctly!!!");
			return SUCCESS;
		}else{
			return ERROR;
		}

	}
	
	private Vehicle updateVehicleSession(Vehicle vehicleForm, Vehicle vehicleSession){
		System.out.println("Vehicle Address " + vehicleForm.getAddress().getStreet() + " - Country : " +  vehicleForm.getAddress().getCountry().getCountry() );

		if(vehicleForm.getAddress()!=null){
			vehicleSession.setAddress(vehicleForm.getAddress());
		}
		
		if(vehicleForm.getCharacteristics()!=null){
			vehicleSession.setCharacteristics(vehicleForm.getCharacteristics());
		}
		
		if(vehicleForm.getCommonUsage()!=null){
			vehicleSession.setCommonUsage(vehicleForm.getCommonUsage());
		}
		
		if(vehicleForm.getConditions()!=null){
			vehicleSession.setConditions(vehicleForm.getConditions());
		}
		
		if(vehicleForm.getCurrency()!=null){
			vehicleSession.setCurrency(vehicleForm.getCurrency());
		}
		
		if(vehicleForm.getCylindersNumber()!=0){
			vehicleSession.setCylindersNumber(vehicleForm.getCylindersNumber());
		}
		
		if(vehicleForm.getDealType()!=null){
			vehicleSession.setDealType(vehicleForm.getDealType());
		}
		
		if(vehicleForm.getDescription()!=null){
			vehicleSession.setDescription(vehicleForm.getDescription());
		}
		
		if(vehicleForm.getDoorsNumber()!=0){
			vehicleSession.setDoorsNumber(vehicleForm.getDoorsNumber());
		}
		
		if(vehicleForm.getEquipment()!=null){
			vehicleSession.setEquipment(vehicleForm.getEquipment());
		}
		
		if(vehicleForm.getExteriorColor()!=null){
			vehicleSession.setExteriorColor(vehicleForm.getExteriorColor());
		}
		
		if(vehicleForm.getInteriorColor()!=null){
			vehicleSession.setInteriorColor(vehicleForm.getInteriorColor());
		}
		
		if(vehicleForm.getMileage()!=0){
			vehicleSession.setMileage(vehicleForm.getMileage());
		}
		
		if(vehicleForm.getPrice()!=0){
			vehicleSession.setPrice(vehicleForm.getPrice());
		}
		
		if(vehicleForm.getSeatMaterial()!=null){
			vehicleSession.setSeatMaterial(vehicleForm.getSeatMaterial());
		}
		
		if(vehicleForm.getSpecialOptions()!=null){
			vehicleSession.setSpecialOptions(vehicleForm.getSpecialOptions());
		}
		
		if(vehicleForm.getTransmisionType()!=null){
			vehicleSession.setTransmisionType(vehicleForm.getTransmisionType());
		}
		
		if(vehicleForm.getEquipment().getEquipment()!=null){
			vehicleSession.getEquipment().setEquipment(vehicleForm.getEquipment().getEquipment());
		}
		
		/*if(vehicleForm.getVersionSubModel()!=null){
			vehicleSession.setVersionSubModel(vehicleForm.getVersionSubModel());
		}
		
		if(vehicleForm.getYear()!=null){
			vehicleSession.setYear(vehicleForm.getYear());
		}*/
		
		return vehicleSession;
	}

	public String[] getComfortAttributesListSelected() {
		String[] ComfortAttributesListSelected=vehicleForm.getEquipment().getCharacteristicsList().get(0).getCharacteristic().split(",");
		System.out.println(ComfortAttributesListSelected.toString());
		return ComfortAttributesListSelected;
	}

	public Vehicle getVehicleForm() {
		return vehicleForm;
	}

	public void setVehicleForm(Vehicle vehicleForm) {
		this.vehicleForm = vehicleForm;
	}

	public Map getSession() {
		return session;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public List<File> getUpload() {
		return upload;
	}

	public void setUpload(List<File> uploads) {
		this.upload = uploads;
	}

	public List<String> getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadsContentType) {
		this.uploadContentType = uploadsContentType;
	}

	public List<String> getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadsFileName) {
		this.uploadFileName = uploadsFileName;
	}

	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}

	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}
	
}
